<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
    <div
      class="max-w-md w-full space-y-8 bg-white p-8 rounded-lg shadow-md transition-all duration-300 hover:shadow-lg"
    >
      <!-- 公共标题区 -->
      <div class="flex flex-col items-center justify-center">
        <img src="@/assets/logo.svg" alt="CMS Logo" class="w-16 h-16 mb-4" />
        <h1 class="text-2xl font-bold text-gray-900 text-center">欢迎回来</h1>
      </div>

      <!-- 动态加载登录组件 -->
      <component
        :is="currentLoginComponent"
        @login-success="handleLoginSuccess"
        :redirect="redirectPath"
        v-bind="currentLoginComponent === WechatOAuthLogin ? { 'auto-trigger': isWeChatBrowser } : {}"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import Cookies from "js-cookie";

// 导入子组件（需显式声明变量用于判断）
import AccountLogin from "./components/AccountLogin.vue";
import WechatOAuthLogin from "./components/WechatOAuthLogin.vue";
import WechatScanLogin from "./components/WechatScanLogin.vue";

const router = useRouter();
const route = useRoute();

// 登录成功后跳转地址
const redirectPath = ref(route.query.redirect || "/index");

// 1. 判断是否为微信内置浏览器（增强判断，排除PC端）
const isWeChatBrowser = computed(() => {
  const ua = navigator.userAgent.toLowerCase();
  const isWeChat = /micromessenger/.test(ua);
  const isPC = /windows nt|macintosh|linux/.test(ua); // 更精确的PC系统判断
  const isMobile = /mobile|android|iphone|ipad|ipod/.test(ua); // 移动设备判断
  return isWeChat && (isMobile || !isPC); // 微信浏览器且在移动设备或非PC环境
});

// 2. 动态决定显示的登录组件
const currentLoginComponent = computed(() => {
  return isWeChatBrowser.value ? WechatOAuthLogin : AccountLogin;
});

// 3. 统一处理登录成功事件
const handleLoginSuccess = (loginData) => {
  console.log("登录成功：", loginData);
  const { token, username, nickname, headimgurl } = loginData;
  if (token) Cookies.set("ut", token);
  if (username || nickname) Cookies.set("un", username || nickname);
  if (headimgurl) Cookies.set("avatar", headimgurl);
  ElMessage.success("登录成功，正在跳转...");
  
  // 修复跳转逻辑：确保跳转到正确的路径
  setTimeout(() => {
    router.push(redirectPath.value).catch(err => {
      console.error("路由跳转失败:", err);
      // 如果路由跳转失败，尝试直接跳转
      window.location.href = redirectPath.value;
    });
  }, 500);
};
</script>